import sys
from PySide6.QtWidgets import (
    QApplication, 
    QMainWindow, 
    QTableView
)
from PySide6.QtCore import QSize
from PySide6.QtSql import QSqlDatabase, QSqlRelationalTableModel, QSqlRelation, QSqlRelationalDelegate

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口标题
        self.setWindowTitle("Python")

        # 创建 QTableView 用于显示数据库表数据
        self.table = QTableView()
        self.setMinimumSize(QSize(1024, 600))
        self.setCentralWidget(self.table)

        # 初始化数据库
        if self.initDb():
            self.model = QSqlRelationalTableModel(db=self.db)
            self.table.setModel(self.model)
            self.model.setTable("Track")
            self.model.setRelation(2, QSqlRelation("Album", "AlbumId", "Title"))
            self.model.setRelation(3, QSqlRelation("MediaType", "MediaTypeId", "Name"))
            self.model.setRelation(4, QSqlRelation("Genre", "GenreId", "Name"))
            delegate = QSqlRelationalDelegate(self.table)
            self.table.setItemDelegate(delegate)
            self.model.select()

    def initDb(self):
        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("Chinook_Sqlite.sqlite")

        if not self.db.open():
            print("Cannot open database.")
            return False
        
        return True


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
